package com.xmy.aboutIO;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Scanner;

// File 类的使用
public class Demo1 {
    public static void main(String[] args) throws IOException {

        //======================文件的创建和删除======================
        File file = new File("E:\\IdeaProjects\\test.txt");

        if (file.exists()) {

            System.out.println(file.getName() + " exists, but we delete it");

            System.out.println(file.getPath()); //返回构造方法传入的路径
            System.out.println(file.getAbsolutePath()); // 返回绝对路径
            System.out.println(file.getCanonicalPath());    // 规范路径

            file.delete();      //delete the file
        } else {
            try {
                System.out.println("file " + file.getName() + " doesn't exist, and we create it.");

                file.createNewFile();       // create a file

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //创建临时文件
        File file0 = File.createTempFile("tmp", ".txt");    // 临时文件的前缀tmp，后缀.txt

        file0.deleteOnExit();   // JVM退出时自动删除临时文件

        System.out.println(file0.isFile());

        System.out.println(file0.getAbsolutePath());

        // ===============文件和目录===================================

        File file2 = new File("C:\\Windows");
        System.out.println(file2.isFile());
        System.out.println(file2.isDirectory());


        String pathName = "E:"+ File.separator +"IdeaProjects";

        File file1 = new File(pathName);

        String[] names = file1.list();  // 获取该路径下的文件和文件名

        File[] fileNames = file1.listFiles();   // 获取目录及文件名，包括隐藏文件

        printFiles(fileNames);

        File file3 = new File("E:\\IdeaProjects\\Hello\\IO\\src\\com\\xmy\\aboutIO");
        System.out.println(file3);

        File[] files = file3.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {

                return name.endsWith(".java");
            }
        });

        printFiles(files);
    }


    static void printFiles(File[] files) {
        if (files != null) {
            for (File f :
                    files)
                System.out.println(f.getName());
        }
    }
}
